package com.dd.cloud.user.service.log.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.cloud.common.exception.ZekeException;
import com.dd.cloud.common.utils.ExtUtils;
import com.dd.cloud.user.entity.log.LogModul;
import com.dd.cloud.user.mapper.log.LogModulMapper;
import com.dd.cloud.user.service.log.ILogModulService;
import com.dd.cloud.user.vo.LogModulExcel;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author czg
 * @since 2022-04-27
 */
@Service
public class LogModulServiceImpl extends ServiceImpl<LogModulMapper, LogModul> implements ILogModulService {
    /**
     * 导入日志模板信息
     *
     * @param file
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importLogModul(MultipartFile file) {
        List<LogModulExcel> list;
        try {
            if (file == null) {
                throw new ZekeException(400, "请上传文件");
            }
            list = ExtUtils.importExcel(file, 0, 1, LogModulExcel.class);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ZekeException(400, "解析Excel失败");
        }
        List<LogModul> saveOrUpdateList = new ArrayList<>();
        QueryWrapper<LogModul> qw = new QueryWrapper<>();
        for (LogModulExcel item : list) {
            qw.clear();
            qw.lambda().eq(LogModul::getUrl, item.getUrl());
            LogModul logModul = getOne(qw);
            if (logModul == null) {
                logModul = new LogModul();
                logModul.setUrl(item.getUrl());
            }
            logModul.setModular(item.getModular());
            logModul.setType(item.getType());
            logModul.setRemarks(item.getRemarks());
            logModul.setOperDesc(item.getOperDesc());
            saveOrUpdateList.add(logModul);
        }
        saveOrUpdateBatch(saveOrUpdateList);
    }

    /**
     * 查询日志模板信息通过url
     *
     * @param url
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public LogModul getLogModulByUrl(String url) {
        QueryWrapper<LogModul> qw = new QueryWrapper<>();
        qw.lambda().eq(LogModul::getUrl, url);
        LogModul logModul = getOne(qw);
        if (logModul == null) {
            logModul = new LogModul();
            logModul.setUrl(url);
            logModul.setModular("待补全");
            logModul.setOperDesc("待补全");
            logModul.setRemarks("待补全");
            save(logModul);
        }
        return logModul;
    }
}
